import logging

from django.core.paginator import Paginator
from django.db import DatabaseError
from django.db.models import Q
from django.http import JsonResponse
from django.shortcuts import redirect

from carsearch.mappers import RecordMapper
from carsearch.models import Record


def index(request):
    return redirect('/static/html/index.html')


def search(request):
    """查询"""
    context = {
        'searched': False,
        'current_page': 1,
        'total_page': 0,
        'records': [],
    }
    carno = request.GET.get('carno', '')
    carno = carno.replace(' ', '').upper()
    page = int(request.GET.get('page', '1'))
    if carno:
        context['searched'] = True
        queryset = Record.objects.filter(
            Q(car__carno__startswith=carno) |
            Q(car__owner__contains=carno)
        ).select_related('car').order_by('-offend_time')
        paginator = Paginator(queryset, 5)
        context['total_page'] = paginator.num_pages
        page_obj = paginator.get_page(page)
        context['current_page'] = page_obj.number
        records = [RecordMapper(record).as_dict()
                   for record in page_obj.object_list]
        context['records'] = records
    return JsonResponse(context)


def handle(request):
    """受理违章记录"""
    data = {'code': 101, 'message': '受理失败'}
    rno = int(request.GET.get('rno', '0'))
    try:
        record = Record.objects.filter(no=rno).first()
        if record:
            if not record.dealed:
                record.dealed = True
                record.save()
            data = {'code': 100, 'message': '受理成功'}
    except DatabaseError as err:
        logging.error(str(err))
    return JsonResponse(data)
